package com.liao.mapth;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ProviderInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;


import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.TileOverlayOptions;
import com.amap.api.maps.model.UrlTileProvider;
import com.amap.api.maps.AMap.OnMarkerClickListener;

import org.json.JSONException;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class LocationActivity extends AppCompatActivity implements OnMarkerClickListener {
    private AMap aMap;
    private MapView mapView;

    //绘图按钮
    private Button Drawline;

    private MarkerOptions markerOptions; ///marker相关

    private Linecollect linecollect = new Linecollect();

    private final String LINE_ELECTR="electr";
    private final String LINE_GAS="gas";
    private final String LINE_RAIN="rian";
    private final String LINE_WASTE="waste";
    private final String LINE_COMMUN="communication";

    private TextView mLocationErrText;
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        requestWindowFeature(Window.FEATURE_NO_TITLE);// 不显示程序的标题栏
        setContentView(R.layout.activity_location);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        init();

        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(16);
        aMap.moveCamera(cameraUpdate);


        Drawline = (Button)findViewById(R.id.drawline);
        Drawline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.v("ss","onclidk");
            }

        });
        initMarker();
        if(savedInstanceState != null){
            linecollect.Stelectric = savedInstanceState.getString(LINE_ELECTR);

        }

        ///http请求
        new MobileQuery().execute("http");
        ///画图
    }
    //TODO 点击回传
    @Override
    public boolean onMarkerClick(Marker marker) {
        Toast.makeText(LocationActivity.this, "您点击了Marker", Toast.LENGTH_LONG).show();
        String id= marker.getTitle();
        Log.i("marker",id);
        Toform(id);
        return false;
    }

    public void Toform(String data){
        Context context = LocationActivity.this;

        Class formActivity = FormActivity.class;

        Intent startFormActivityIntent = new Intent(context,formActivity);
        startFormActivityIntent.putExtra(Intent.EXTRA_TEXT,data);
        startActivity(startFormActivityIntent);

    }

    public class MobileQuery extends AsyncTask<String,Void,Linecollect>{

        @Override
        protected Linecollect doInBackground(String... params) {

            Linecollect BKlinecollect =new Linecollect();

            Line line = new Line("http://192.168.43.71:8080/mobile/elect");
            //加载电力线;
            try{
                if(linecollect.Stelectric.equals("")) {
                    BKlinecollect.Stelectric = line.getLinejson();   //获取json
                    //序列化
                }else {
                    BKlinecollect.Stelectric = linecollect.Stelectric;

                }
                BKlinecollect.electric = line.parseLine(BKlinecollect.Stelectric);
            } catch (IOException e){
                e.printStackTrace();
                Log.v("err","电力----IO");
            } catch (JSONException e){
                e.printStackTrace();
                Log.v("err","电力----JSON");
            }



            Log.v("hui","画图成功");

            return BKlinecollect;
        }
        @Override
        protected void onPostExecute(Linecollect line){
            if (line.electric != null && !line.electric.equals("")) {
                linecollect = line;
               ///加载电力线
                //LatLng a = new LatLng(data.get(1).latitude,data.get(1).longitude);

                for (int i=0;i<line.electric.length;i++) {
                    aMap.addPolyline(new PolylineOptions().
                            addAll(line.electric[i]).width(10).color(Color.argb(255, 1, 1, 1)));
                }

                LatLng a =new LatLng(30.518141,114.398951);
                CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(a,18,0,0));
                aMap.moveCamera(cameraUpdate);
            }
        }
    }
    /*public Line line; */ //点一直存在内存里
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }

    }
    //TODO marker
    private void initMarker(){
        aMap.setOnMarkerClickListener(this);
        markerOptions = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
                .position(new LatLng(30.520583,114.398341))
                .title("1");    //marker

         aMap.addMarker(markerOptions);

    }



/*    public List<LatLng> Getines() throws IOException,JSONException {
        Log.i("test","strat getlines")
        String jsondata = httpquest.get("http://172.31.34.66:3000/mobile");  //从后台获取数据

        JSONObject jsonObjectgeom = new JSONArray(jsondata)
                .getJSONObject(0)
                .getJSONObject("geom");
        List<LineString> lines = new MultiLineString(jsonObjectgeom)
                .getLineStrings();  //转成线

        List<LatLng> latLngs = new ArrayList<LatLng>();


        for(LineString lineString : lines){
            double lat =lineString.getPositions().get(0).getLatitude();
            double lng = lineString.getPositions().get(0).getLongitude();
            latLngs.add(new LatLng(lat,lng));

        }


        return  latLngs;
    }*/

    private void setUpMap() {
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        setupLocationStyle();

    }

    private void setupLocationStyle(){
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
      /*  myLocationStyle.myLocationIcon(BitmapDescriptorFactory.
                fromResource(R.drawable.gps_point));*/

        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE) ;//定位一次，且将视角移动到地图中心点。
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(STROKE_COLOR);
        //自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(5);
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(FILL_COLOR);
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    ///TODO(1)  Override onSaveInstanceState
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
        outState.putString(LINE_ELECTR,linecollect.Stelectric);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }



}
